import axios from "axios"
import Vue from "vue"
import vueRouter from "@/router/"
import {
    Message
} from "element-ui"
Vue.$message = Message
const api = axios.create({
    baseURL: process.env.HOST,
    timeout: 9000,
    withCredentials: true
})

api.interceptors.response.use(response => {
    let {
        code,
        msg,
        success,
        commonResponse
    } = response.data
    if (code === 200 || success || commonResponse) {
        return response
    } else if (code === 402 || code === 503) {
        // let onoff = Boolean(~response.request.responseURL.indexOf("/"))
        // if (!onoff) {
        vueRouter.replace("/login")
        // }
        return response
    } else {
        Vue.$message({
            message: msg,
            type: "warning"
        })
        return new Error("请求失败")
    }
}, error => {
    return Promise.reject(error)
})

export default api

export const importApi = (Vue) => {
    Object.defineProperty(Vue.prototype, "$api", {
        value: api
    })
}
